package jsp.dao;

import jsp.model.User;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class UserDao extends BaseDao {

    public List<User> selectList() throws Exception {
        StringBuilder sb = new StringBuilder("select * from jsp_user");
        return executeQuery(sb.toString(),new Object[]{});
    }

    public List<User> selectList(User user) throws Exception {
        StringBuilder sb = new StringBuilder("select * from jsp_user where 1=1 ");
        List<Object> params = new ArrayList<>();

        if (user.getId() != null) {
            sb.append(" and id = ?");
            params.add(user.getId());
        }

        if (user.getName() != null) {
            sb.append(" and name like ?");
            params.add("%" + user.getName() + "%");
        }

        return executeQuery(sb.toString(), params.toArray());
    }


    public int insert(User user) throws Exception {
        String sql = "insert into jsp_user(name, username, password, role) values(?, ?, ?, ?)";
        return executeUpdate(sql, new Object[]{user.getName(), user.getUsername(), user.getPassword(), user.getRole()});
    }

    public int update(User user) throws Exception {
        String sql = "update jsp_user set name = ?, username = ?, password = ? where id = ?";
        return executeUpdate(sql, new Object[]{user.getName(), user.getUsername(), user.getPassword(), user.getId()});
    }

    public int deleteById(int id) throws Exception {
        String sql = "delete from jsp_user where id = ?";
        return executeUpdate(sql, new Object[]{id});
    }


    public User selectById(int id) throws Exception {
        String sql = "select * from jsp_user where id = ?";
        List<User> list = executeQuery(sql, new Object[]{id});
        return list.isEmpty() ? null : list.get(0);
    }


    @Override
    public Object rowToObject(ResultSet rs) throws Exception {
        return new User(rs.getInt("id"),
                rs.getString("name"),
                rs.getString("username"),
                rs.getString("password"),
                rs.getString("role")
        );
    }

    public User selectByUsernamePassword(String username, String password) throws Exception {
        String sql = "select * from jsp_user where username = ? and password = ?";
        List<User> list = executeQuery(sql, new Object[]{username, password});
        return list == null || list.isEmpty() ? null : list.get(0);
    }

    public User selectByUsername(String username) throws Exception {
        String sql = "select * from jsp_user where username = ?";
        List<User> list = executeQuery(sql, new Object[]{username});
        return list == null || list.isEmpty() ? null : list.get(0);
    }
}
